package com.wushijia.sql;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.ConnectionFactory;
import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDataSource;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;

public class DbUtil {

  private static DataSource dataSource;

  static {
    try {
      InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
      Properties properties = new Properties();
      properties.load(in);           // 返回数据源对象
      dataSource = setupDataSource(properties.getProperty("url"), properties);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static DataSource getDataSource() {
    return dataSource;
  }

  public static Connection getConnection() {
    try {
      return dataSource.getConnection();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  private
  static DataSource setupDataSource(final String connectionUri, final Properties properties) {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionUri, properties);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool);
    return dataSource;
  }
}
